###############################################################################
#
# Copyright (c) 2011 Rainmaker Entertainment
# All Rights Reserved.
#
# This file contains unpublished confidential and proprietary
# information of Rainmaker Entertainment.  The contents of this file
# may not be copied or duplicated, in whole or in part, by any
# means, electronic or hardcopy, without the express prior
# written permission of Rainmaker Entertainment.
#
#    $HeadURL: http://pt/src/trunk/maya/outsource/rnkOutsourceChecker/operations/rig.py $
#    $Revision: 68809 $
#    $Author: wmakari $
#    $Date: 2013-10-25 17:18:54 -0700 (Fri, 25 Oct 2013) $
#
###############################################################################

###############################################################################
## INFOS
###############################################################################

# Geo checks


###############################################################################
## MODULES
###############################################################################

import traceback
import re

try :
    import maya.cmds as cmds
    import maya.mel as mel
    import maya.OpenMaya as OpenMaya
except :
    traceback.print_exc()
    print "Can't load Maya modules."
    

import core
reload(core)

import rnkAssetChecks.rig as rnkAssetChecksRig
reload(rnkAssetChecksRig)

###############################################################################
## FUNCTIONS
###############################################################################  

def checkInfoCtrl(assetRoot, *args, **kw):
    """ 
    @brief Check if the sets containing the controllers list exists.
    @return : Bool
    
    ARGS :
            @param assetRoot - String - Asset root node.
    """
    issues = []
    controllersSets = ['set_ctrl']
    for eachSet in controllersSets :
        if not cmds.objExists(eachSet):
            issues.append(eachSet)

    if not issues:
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else :
        return core.checkResult(allowPublish=False, msg="Please make a controller set. Name should be set_ctrl.", nodes=issues)

checkInfoCtrl.modifiedScene = False
checkInfoCtrl.uiName = 'Check if set_ctrl exists'
checkInfoCtrl.revision = "$Revision: 68809 $".split()[1]



def checkControllerAttributesWithInput(assetRoot, *args, **kw):
    """ 
    @brief List controllers whose animatable attributes have an input connection.
    @return : Set
    
    ARGS :
            @param assetRoot - String - Asset root node.
    """

    # list nodes which attributes have input.
    issues = []

    controllers = core.getCtrlList(assetRoot)
    if not len(controllers) == 0 :
        for controller in controllers:
            if cmds.objExists('%s.allowPublishWithConnections' % controller) is True:
                continue
    
            attrs = core.listStorableAttrs(controller)
            if not attrs is None :
                for attr in attrs:
                    input = []
                    input = cmds.listConnections("%s.%s" %(controller, attr), s=True, d=False)
                    if input:
                        issues.append("%s.%s" %(controller, attr))


    if len(issues) == 0 :
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else :
        return core.checkResult(allowPublish=False, msg="Those animatable attributes have an input connection", nodes=issues)

checkControllerAttributesWithInput.modifiedScene = False
checkControllerAttributesWithInput.uiName = 'Check Controllers Animatable Attributes Input'
checkControllerAttributesWithInput.revision = "$Revision: 68809 $".split()[1]



def checkControllerLockedAttributes(assetRoot, *args, **kw):
    """ 
    @brief List controllers whose animatable attributes are locked
    @return : List
    
    ARGS :
            @param assetRoot - String - Asset root node.
    """

    # list nodes which attributes have input.
    issues = []
    attrsSet = set()

    controllers = core.getCtrlList(assetRoot)
    if not len(controllers) == 0 :
        for controller in controllers:
            attrs = core.listStorableAttrs(controller)
            for attr in attrs:
                if cmds.getAttr("%s.%s" % (controller, attr), lock=True) is True :
                    issues.append("%s.%s" % (controller, attr))

    if len(issues) == 0 :
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else :
        return core.checkResult(allowPublish=False, msg="Those animatable attributes are locked", nodes=issues)

checkControllerLockedAttributes.modifiedScene = False
checkControllerLockedAttributes.uiName = 'Check Controllers Animatable Attributes Lock State'
checkControllerLockedAttributes.revision = "$Revision: 68809 $".split()[1]



def checkNonAnimatableAttr(assetRoot, *args, **kw):
    """ 
    @brief Check if the non-animatable attribute are locked and hidden
    @return : List

    ARGS :
        @param assetRoot - String - Asset root node.
    """

    ## Non-Normalize list
    nonLocked = []

    ## Get all skinClusters
    getCtrls = core.getCtrlList(assetRoot)
    for ctrl in getCtrls :
        if cmds.listAttr(ctrl, channelBox=True):
            nonLocked.append(ctrl)

    if nonLocked:
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else :
        return core.checkResult(allowPublish=True, warning=True, msg="Those non-animatable attributes are not locked or/and hidden", nodes=nonLocked)

checkNonAnimatableAttr.modifiedScene = False
checkNonAnimatableAttr.uiName = 'Check Controllers non-Animatable Attributes'  
checkNonAnimatableAttr.revision = "$Revision: 68809 $".split()[1]



def checkSwitchCtrl(assetRoot, *args, **kw):
    """ 
    @brief Check if the main switch controller exists.
    @return : Bool
    
    ARGS :
            @param assetRoot - String - Asset root node.
    """

    getCtrls = core.getCtrlList(assetRoot)

    if 'c_mxnswitch_ctl' in getCtrls :  
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else :
        return core.checkResult(allowPublish=False, msg="Can't find 'c_mxnswitch_ctl', make sure it exists or/and is in the controllers set", nodes=['c_mxnswitch_ctl'])

checkSwitchCtrl.modifiedScene = False
checkSwitchCtrl.uiName = 'Check Switch Controller'
checkSwitchCtrl.revision = "$Revision: 68809 $".split()[1]



def checkGlobalLocal(assetRoot, *args, **kw):
    """ 
    @brief Check if the global and local controllers exists.
    @return : List
    
    ARGS :
            @param assetRoot - String - Asset root node.
    """
    
    missingCtrl = []
    
    getCtrls = core.getCtrlList(assetRoot)
    if not len(getCtrls) == 0 :
        for each in ['globalTrans', 'globalTransA', 'globalTransB', 'localTrans'] :
            if not each in getCtrls :
                missingCtrl.append(each)

    if len(missingCtrl) == 0 :
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else :
        return core.checkResult(allowPublish=False, msg="Those controllers either don't exists or are not in the controllers set", nodes=missingCtrl)

checkGlobalLocal.modifiedScene = False
checkGlobalLocal.uiName = 'Check Global/Local Controllers'
checkGlobalLocal.revision = "$Revision: 68809 $".split()[1]



def checkNodesNotInContainers(assetRoot, *args, **kw):
    """ 
    @brief Look for nodes outside of containers
    @return : List
    
    ARGS :
            @param assetRoot - String - Asset root node.
    """
    
    issues = rnkAssetChecksRig.checkNodesNotInContainers(assetRoot)
    

    if len(issues) == 0 :
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else :
        return core.checkResult(allowPublish=False, msg="Those nodes are not in one of the containers", nodes=issues)

checkNodesNotInContainers.modifiedScene = False
checkNodesNotInContainers.uiName = 'Check Nodes Outside Of Containers'
checkNodesNotInContainers.revision = "$Revision: 68809 $".split()[1]


def checkNonNormalizedWeights(assetRoot, *args, **kw):
    """ 
    @brief Check Non-Normalized weights
    @return : List
    
    ARGS :
            @param assetRoot - String - Asset root node.
    """
    
    issues = rnkAssetChecksRig.checkNonNormalizedWeights()
    

    if len(issues) == 0 :
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else :
        return core.checkResult(allowPublish=True, warning=True, msg="Those weights are not normalized", nodes=issues)

checkNonNormalizedWeights.modifiedScene = False
checkNonNormalizedWeights.uiName = 'Check non-normalized weights'
checkNonNormalizedWeights.revision = "$Revision: 68809 $".split()[1]



def checkNanErrors(assetRoot, *args, **kw):
    """ 
    @brief Check if any skinCluster can make nan error when the file is saved
    @return : List
    
    ARGS :
            @param assetRoot - String - Asset root node.
    """
    issues = rnkAssetChecksRig.checkNanErrors()


    if len(issues) == 0 :
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else :
        return core.checkResult(allowPublish=False, msg="These skinClusters will generate Nan errors while saving.", nodes=issues)

checkNanErrors.modifiedScene = False
checkNanErrors.uiName = 'Check Nan errors on skinClusters'
checkNanErrors.revision = "$Revision: 68809 $".split()[1]


def geoExists(*args, **kw):
    """
    """
    if cmds.ls("geo"):
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else :
        return core.checkResult(allowPublish=False, msg="geo group doesn't exist.")
geoExists.modifiedScene = False
geoExists.uiName = 'Check if geo group exists'
geoExists.revision = "$Revision: 68809 $".split()[1]


def listDisplayLayers(*args, **kw):
    """
    Check if there are display layers in the scene. Exception: displayLayer for eyes.
    """
listDisplayLayers.modifiedScene = False
listDisplayLayers.uiName = 'Check Nan errors on skinClusters'
listDisplayLayers.revision = "$Revision: 68809 $".split()[1]
